import { StackActions, useNavigation } from '@react-navigation/native';
import { useDispatch, useSelector } from 'react-redux';

import { getDefaultPaywallConfig } from '@constants/paywall.ts';
import { ToastMessage } from '@utils/toastMessage.ts';

import { getPriceAndCurrency, preloadSubscriptionVideos } from './utils';
import { paymentAPI } from '@/api/paymentAPI.ts';
import { userAPI } from '@/api/userAPI.ts';
import { PERMANENT_PRODUCT_ID, WEEKLY_PRODUCT_ID } from '@/constants';
import { setPaywallConfig, setPaywallProductDetailList, setPaywallRouteName } from '@/stores/slice/paywallSlice.ts';
import { RootState } from '@/stores/store';
import { getCurrentState } from '@/utils';
import { FirebaseEventsUtil } from '@/utils/analytics';
import PayServer from '@/utils/pay';

//  周订阅映射
const subscriptionMap: Record<string, string> = {
  'redoze_weekly_6.99': 'redoze_weekly_4.99',
};

export const useGetReadyPaywall = () => {
  const dispatch = useDispatch();
  const navigation = useNavigation();
  const { paywallRouteName } = useSelector((state: RootState) => state.paywall);
  const payServerInstance = PayServer.getInstance();
  /** 获取产品列表 */
  const handleGetProductList = async (
    codes: string[] = [WEEKLY_PRODUCT_ID, PERMANENT_PRODUCT_ID], // 默认周费和永久产品
  ) => {
    try {
      const productList = await paymentAPI.getProductDetailList({ codes });
      if (productList.code !== 0) {
        ToastMessage.warning(productList.msg || 'Failed to get user product detail, please try again');
        return [];
      }
      return productList.data ?? [];
    } catch (error) {
      ToastMessage.warning((error as Error).message || 'Failed to get user product detail, please try again');
      return [];
    }
  };
  /** 获取Paywall 信息 */
  const handleGetPaywall = async () => {
    try {
      const res = await userAPI.get_user_products();
      if (res.code !== 0) {
        ToastMessage.warning(res.msg || 'Failed to get user paywallId');
        return;
      }

      return {
        codes: res.data?.codes ?? [],
        paWallId: res.data?.paWallId ?? '',
      };
    } catch (error) {
      console.error('Failed to get user paywallId:', error);
      ToastMessage.warning('Failed to get user paywallId, please try again');
    }
  };
  /** 获取Paywall 配置 */
  const handleGetPaywallConfig = async (paywallId?: string) => {
    if (!paywallId) {
      console.warn('paywallId is empty');
      return;
    }

    try {
      const paywallRes = await paymentAPI.getPaywallDetail({
        paywallIds: [paywallId],
      });

      if (paywallRes.code !== 0) {
        return;
      }
      if (!paywallRes.data || paywallRes.data.length === 0) {
        return;
      }
      const paywallConfigStr = paywallRes.data[0]?.jsonStr;

      if (!paywallConfigStr) {
        return;
      }
      const paywallConfig: Paywall.PaywallConfig = JSON.parse(paywallConfigStr);
      return paywallConfig;
    } catch (error) {
      console.error('Failed to get user paywall:', error);
      ToastMessage.warning('Failed to get user paywall');
    }
  };

  /** 加载订阅页面所需的数据，返回Paywall配置 */
  const getPayWallConfig = async () => {
    const paywall = await handleGetPaywall();

    const paywallConfig = await handleGetPaywallConfig(paywall?.paWallId);

    preloadSubscriptionVideos(paywallConfig);

    const PayWallConfig = paywallConfig ?? getDefaultPaywallConfig();

    const productList: Payment.ProductDetailInstance[] = await handleGetProductList(paywall?.codes ?? []);

    const products = await payServerInstance.getAllProducts(
      productList.map((item) => subscriptionMap[item.code] ?? item.code) ?? [],
    );
    productList.forEach((product) => {
      // 映射
      const code = subscriptionMap[product.code] ?? product.code;
      const payProduct = products.find((item) => item.productId === code);
      const priceAndCurrency = getPriceAndCurrency(payProduct);
      if (payProduct && priceAndCurrency) product.details = priceAndCurrency;
    });
    dispatch(setPaywallConfig(PayWallConfig));
    dispatch(setPaywallProductDetailList(productList));
    dispatch(setPaywallRouteName(PayWallConfig.subscriptionRoute.name));

    return PayWallConfig; // 返回配置以供后续使用
  };

  /** 跳转到订阅页 */
  const handleToSubscription = () => {
    const state = navigation.getState();
    if (state) {
      const name = getCurrentState(state).name;
      FirebaseEventsUtil.goto_subscription(name ?? '', paywallRouteName);
    }
    navigation.dispatch(StackActions.push(paywallRouteName));
  };

  return {
    getPayWallConfig,
    preloadSubscriptionVideos,
    handleToSubscription,
  };
};
